package come.bjpowernode.javase.homework;
/*
1、使用生产者和消费者实现，交替输出
    假设只有两个线程，输出以下结果：
        t1-->1
        t2-->2
        t1-->3
        t2-->4
 */
public class Homework {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        int[] a = {0};
        Thread t1 = new Thread(new Printer1(a));
        Thread t2 = new Thread(new Printer2(a));

        t1.setName("t1");
        t2.setName("t2");

        t1.start();
        t2.start();
    }
}

class Printer1 implements Runnable {
    private int[] a = {0};
    public Printer1(int[] a){
        this.a = a;
    }
    @Override
    public void run() {
        while(true){
            synchronized(a){
                if (a[0]%2 == 1){
                    try {
                        a.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                a[0] = a[0] +1;
                System.out.println(Thread.currentThread().getName()+
                        "-->"+ a[0]);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a.notify();
            }
        }
    }
}

class Printer2 implements Runnable{
    private int[] a = {0};
    public Printer2(int[] a){
        this.a = a;
    }
    @Override
    public void run() {
        while(true){
            synchronized(a){
                if (a[0]%2 == 0){
                    try {
                        a.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                a[0] = a[0] + 1;
                System.out.println(Thread.currentThread().getName()+
                        "-->"+ a[0]);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a.notify();
            }
        }

    }
}
